package com.jams.goodox;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jams.goodox.activity.IBaseActFrag;
import com.jams.goodox.activity.common.SimpleHtmlActivity;
import com.jams.goodox.activity.login.LoginActivity;
import com.jams.goodox.entity.ServerBean;
import com.jams.goodox.listen.CustomShareListener;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.RetrofitHelper;
import com.jams.goodox.utils.DeviceUtils;
import com.jams.goodox.widget.LoadingDialog;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * ClassName:BaseActivity <br/>
 * Date: 2017年4月14日 下午17:07 <br/>
 *
 * @author
 */
public abstract class BaseActivity extends AppCompatActivity implements IBaseActFrag {

    public static final int THUMB_SIZE = 150;
    public Context mContext;
    private RetrofitHelper retrofitHelper;
    protected View titleBar;
    private LoadingDialog loadingDialog;//加载圈
    public String LOG_CAT = "ailee";

    private Snackbar snackbar;

    IntentFilter intentFilter;
    protected Map<String, Object> params = new HashMap<>();
    protected Gson gson=new Gson();

    protected IWXAPI api;
    protected AuthInfo authInfo;
    public static final String SCOPE =
            "email,direct_messages_read,direct_messages_write,"
                    + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
                    + "follow_app_official_microblog," + "invitation_write";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_layout_with_title);

        mContext = this;
        titleBar = findViewById(R.id.base_action_bar);
        setTitleVisibility(true);
        FrameLayout contentLayout = (FrameLayout) findViewById(R.id.content_layout);
        LayoutInflater.from(this).inflate(getLayoutId(), contentLayout, true);
        ButterKnife.bind(this);
        retrofitHelper = RetrofitHelper.get(this);//初始化

        api = WXAPIFactory.createWXAPI(this, BuildConfig.WEIXIN_APPID);
        api.registerApp(BuildConfig.WEIXIN_APPID);

        WbSdk.install(this,new AuthInfo(this, BuildConfig.WB_APPID,
                "\"http://www.sina.com\"", SCOPE));

        authInfo = new AuthInfo(this,BuildConfig.WB_APPID,
                "\"http://www.sina.com\"",SCOPE);

        init();
    }

    //分享弹框
    protected void showSharePop(final CustomShareListener customShareListener){
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_share_weixin_view, null);
        // 设置style 控制默认dialog带来的边距问题
        final Dialog dialog = new Dialog(this, R.style.common_dialog);
        dialog.setContentView(view);
        dialog.show();

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.share_wx:
                        // 分享到微信
                        customShareListener.onShareCallBack(1);
                        dialog.dismiss();
                        break;
                    case R.id.share_circle:
                        // 分享到朋友圈
                        customShareListener.onShareCallBack(2);
                        dialog.dismiss();
                        break;
                    case R.id.share_wb:
                        customShareListener.onShareCallBack(3);
                        dialog.dismiss();
                        break;

                    case R.id.share_link:
                        customShareListener.onShareCallBack(4);
                        dialog.dismiss();
                        break;
                    case R.id.share_cancel_btn:
                        // 取消
                        dialog.dismiss();
                        break;

                }
                dialog.dismiss();

            }
        };

        TextView mViewWeixin = (TextView) view.findViewById(R.id.share_wx);

        TextView mViewPengyou = (TextView) view.findViewById(R.id.share_circle);
        TextView mViewWB = (TextView) view.findViewById(R.id.share_wb);
        TextView share_link = (TextView) view.findViewById(R.id.share_link);
        TextView mBtnCancel = (TextView) view.findViewById(R.id.share_cancel_btn);

        //mBtnCancel.setTextColor(R.color.common_font_color_2);

        mViewWeixin.setOnClickListener(listener);
        mViewPengyou.setOnClickListener(listener);
        mViewWB.setOnClickListener(listener);
        share_link.setOnClickListener(listener);
        mBtnCancel.setOnClickListener(listener);

        // 设置相关位置,一定要在 show()之后

        Window window = dialog.getWindow();

        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams params = window.getAttributes();

        params.width = ViewGroup.LayoutParams.MATCH_PARENT;

        params.gravity = Gravity.BOTTOM;

        window.setAttributes(params);


    }


    protected void clearMap(){
        params.clear();
        //通用参数
        params.put("sign", "test");
        params.put("uuid", "5617222222");
        params.put("accessToken",SePref.getToken());
        params.put("timeStamp",String.valueOf(System.currentTimeMillis()));
        params.put("version",BuildConfig.VERSION_NAME);
    };


    protected void dealRequest(){

    }


    //设置title是否隐藏
    public void setTitleVisibility(boolean visibility) {
        titleBar.setVisibility(visibility ? View.VISIBLE : View.GONE);
    }

    public View getTitleBar(){
        return titleBar;
    }

    /**
     * 布局文件ID
     */
    protected abstract int getLayoutId();

    /**
     * 初始化
     */
    protected abstract void init();

    public <T> T createCallService(Class<T> apiServiceClass) {
        return ProtocolManagers.getInstance(this).getService(apiServiceClass);
    }

    public <T extends BaseEntity> void enqueue(Call<T> call, RetrofitCallbackListener<T> callback) {
        retrofitHelper.enqueue(call, callback);
    }



    /**
     * 显示菊花
     */
    public void showLoading() {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog.createDialog(this);
        }
        loadingDialog.show();
    }

    public void showLoading(String title) {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog.createDialog(this);
        }
        loadingDialog.setTitile(title);
        loadingDialog.show();

    }

    /**
     * 隐藏菊花
     */
    protected void misLoading() {
        if (this!=null&&!this.isFinishing()&&loadingDialog != null)
            loadingDialog.cancel();
    }

    /**
     * 关闭软键盘
     */
    public void closeKeyboard() {

        /**隐藏软键盘**/
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public void openKeybord() {
        /**打开软键盘**/
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.RESULT_SHOWN);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                    InputMethodManager.HIDE_IMPLICIT_ONLY);
        }
    }

    protected void doBackThing() {
        finish();
    }

    @Override
    public void qStartActivity(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void qStartActivity(Class<? extends Activity> cls) {
        qStartActivity(cls, null);
    }

    @Override
    public void qStartActivity(Class<? extends Activity> cls, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(this, cls);
        startActivity(intent);
    }

    @Override
    public void qStartActivity(ServerBean bean) {

    }

    @Override
    public void qStartActivityForResult(Class<? extends Activity> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(this, cls);
        startActivityForResult(intent, requestCode);
    }

    /* 带结果返回上一个activity， 配合qStartActivityForResult使用 */
    @Override
    public void qBackForResult(int resultCode, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        setResult(resultCode, intent);
        finish();
    }

    @Override
    public void qBackToActivity(Class<? extends Activity> cls, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(this, cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    @Override
    public Context getContext() {
        return mContext;
    }

    @Override
    public Handler getHandler() {
        return null;
    }


    public View getLoadMoreBootView(Context c) {
        View view = LayoutInflater.from(c).inflate(R.layout.load_more_footers, null);
        view.setLayoutParams(new DrawerLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        return view;
    }

    public void cancelAllCall(){
        retrofitHelper.cancelCalls();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        retrofitHelper.cancelCalls();
//        if (intentFilter != null&&myPushReserve!=null) {
//            unregisterReceiver(myPushReserve);
//        }
    }

    /********
     * 推送相关
     *****/
    public class MyPushReserve extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            showShackBar("");
        }
    }

    public void showShackBar(String msg) {
        View view=findViewById(android.R.id.content);
        if (view != null) {
            snackbar = Snackbar.make(view, msg, Snackbar.LENGTH_LONG);
            snackbar.show();
        }
    }

    /**
     * 点击跳转
     *
     * @param msgType
     */
    private void jumpActivity(String msgType) {
        Intent intent = new Intent();
        //是否登录，未登录，进入登陆页
        if (TextUtils.isEmpty(SePref.getToken())) {
            intent.setClass(mContext, LoginActivity.class);
        } else {
            //后台运行，进入首页
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent);
    }

}
